package spotGUI.sideBar.utils;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class SaxHandler extends DefaultHandler {
	
	private static final String CURRENT_WEATHER = "yweather:condition";
	private static final String WEATHER_FORECAST = "yweather:forecast";
	private static final String ITEM = "item";

	private boolean listeningMode = false;
	private WeatherData[] data = new WeatherData[3];
	private int i = 0;
	
	public void startDocument() throws SAXException {
	}

	public void endDocument() throws SAXException {
		XMLWeatherDataReader.getSharedInstance().setWeatherData(data);
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (qName.equals("item")) {
			listeningMode=true;
		}
		if (listeningMode == true && i<data.length) {

			if (qName.equals(CURRENT_WEATHER)) {
				data[i]= new WeatherData();
				data[i].setConditionCode(attributes.getValue("code"));
				data[i].setLowTemperature(attributes.getValue("temp"));
				data[i].setHighTemperature(attributes.getValue("temp"));
				data[i].setDate(attributes.getValue("date"));
				i++;
			} else if (qName.equals(WEATHER_FORECAST)) {
				data[i]= new WeatherData();
				data[i].setConditionCode(attributes.getValue("code"));
				data[i].setLowTemperature(attributes.getValue("low"));
				data[i].setHighTemperature(attributes.getValue("high"));
				data[i].setDate(attributes.getValue("day")+", "+attributes.getValue("date"));
				i++;
			}
		}
	}

	public void endElement(String uri, String localName, String qName)
	throws SAXException {
		if (qName.equals(ITEM)) {
			listeningMode=false;
		}
	}

	public void characters(char ch[], int start, int length)
	throws SAXException {
	}
}
